<template>
  <div>
    <div class="map-container" :style="containerStyle" id="map-container"></div>
    <Layout></Layout>
    <!-- <PolymerizedBasanBuy ref="buyRef"></PolymerizedBasanBuy> -->
    <BasanInfo ref="basanInfoRef"></BasanInfo>
    <CollectedBasanInfo ref="collectedBasanInfoRef"></CollectedBasanInfo>
  </div>
</template>
<script>
import Map from "@/map/index.js";
import * as CONSTANTS from "@/config/constants.js";
import { mapGetters } from "vuex";
import Layout from "@/components/layout/layout.vue";
import { formatDate } from "@/utils/common.js";
import basanApi from "@/server/basan/basan.js";
// import PolymerizedBasanBuy from "@/components/polymerizedBasanBuy/polymerizedBasanBuy.vue";
import BasanInfo from "@/components/basanInfo/basanInfo.vue";
import CollectedBasanInfo from "@/components/collectedBasanInfo/collectedBasanInfo.vue";
import { PlatformEnv } from "@/config/config.js";

export default {
  nmae: "AppMap",
  components: { Layout, CollectedBasanInfo, BasanInfo },
  data() {
    return {
      map: null,
      moveTimeout: null,
      date: "",
      basanLayer: null,
      clickedBasan: null,
      collectedBasanLayer: null,
    };
  },
  computed: {
    ...mapGetters("oceanFeature", ["oceanFeatureList"]),
    ...mapGetters("user", ["isUserLoggedIn"]),
    containerStyle() {
      return PlatformEnv.isAndroid ? { height: 'calc(100% - 92px)', top: '32px' } : PlatformEnv.isWx ? { height: 'calc(100% - 62px)'} : { height: '100%'}
    }
  },
  mounted() {
    this.init();
    // if (PlatformEnv.isAndroid) {
    //   this.$nextTick(() => {
    //     // document.getElementsByClassName(
    //     //   "leaflet-control-colorBar"
    //     // )[0].style.bottom = window.devicePixelRatio > 2 ? "60px" : "65px";
    //     // document.getElementsByClassName(
    //     //   "leaflet-control-colorBar"
    //     // )[0].style.top = "20px";
    //     // document.getElementsByClassName(
    //     //   "leaflet-control-loading-bar"
    //     // )[0].style.top = "20px";
    //   });
    // }

    // document.addEventListener("visibilitychange", () => {
    //   const saveCatchRecords = this.$route.query.saveCatchRecords;
    //   if (PlatformEnv.isWx && !saveCatchRecords && document.visibilityState === "visible") {
    //     window.location.reload();
    //   }
    // });
  },
  beforeDestroy() {
    this.$bus.$off(CONSTANTS.EventEnum.TIMECHANGE);
    this.$bus.$off(CONSTANTS.EventEnum.RESETCLICKEDBASAN);
    this.$bus.$off(CONSTANTS.EventEnum.RADARSCANNING);
    this.$bus.$off(CONSTANTS.EventEnum.COLLECTBASAN);
    this.$bus.$off(CONSTANTS.EventEnum.REMOVECOLLECTEDBASAN);
    // document.removeEventListener("visibilitychange", () => {
    //   const saveCatchRecords = this.$route.query.saveCatchRecords;
    //   if (PlatformEnv.isWx && !saveCatchRecords && document.visibilityState === "visible") {
    //     window.location.reload();
    //   }
    // });
  },
  methods: {
    async init() {
      this.initMap();
      this.initCollectedBasanLayer();
      this.date = formatDate(new Date(), "yyyy-MM-dd");
    },
    initMap() {
      const options = {
        zoomControl: false,
        attributionControl: false,
        minZoom: 5,
        maxZoom: 10,
        zoom: 6,
        center: [25, 145],
      };
      this.map = new Map.LMap("map-container", options);
      const isSyncMode = PlatformEnv.isIos ? false : true;
      // const isSyncMode = false;
      const colorBarOptions = {
        position: PlatformEnv.isWx || PlatformEnv.isAndroid ? "bottomright" : "topright",
      };
      this.map.initProducts({
        isSyncMode,
        colorBar: colorBarOptions,
      });
      this.map.initLayers();
      var colorBar = this.map.getProducts().getColorBar();
      colorBar.addTo(this.map.getLMap());
      this.initOceanLayers();

      this.$nextTick(() => {
        this.$bus.$emit(CONSTANTS.EventEnum.MAPCREATED, this.map);
      });

      //需要map.map才能找到map
      this.setMapListen();

      setTimeout(() => {
        const center = this.map.wrapLatLng(this.map.getCenter());
        // const oceanDataList = this.map.getOceanDataByLatlng(
        //   this.map.wrapLatLng(this.map.getCenter())
        // );
        // this.$store.commit("oceanFeature/updateOceanFeatureData", {
        //   oceanDataList,
        //   oceanFeatureList: this.oceanFeatureList,
        // });
        this.$store.commit("mapState/updateMapCenter", center);
      }, 2000);
    },
    initOceanLayers() {
      this.map.getProducts().getLoadingBar().show();

      this.oceanFeatureList.forEach((oceanFeature) => {
        this.map.createOceanProductLayer(oceanFeature);
      });
    },
    async initCollectedBasanLayer() {
      if (!this.collectedBasanLayer) {
        this.collectedBasanLayer = this.map.createLayerGroup();
        this.map.addLayer(this.collectedBasanLayer);
      }
      const result = await basanApi.queryCollectedBasanList({});
      if (!result.isOk) {
        // this.$notify("获取收藏的钓点失败");
        return;
      }
      const collectedBasanMarkerList = this.createCollectedBasanMarkerList(
        result.data.records
      );
      collectedBasanMarkerList.forEach((marker) => {
        marker.addTo(this.collectedBasanLayer);
      });
    },
    addCollectedBasan() {
      const latlng = this.clickedBasan.getLatLng();
      const basanList = [
        { gid: this.clickedBasan.options.id, lat: latlng.lat, lng: latlng.lng },
      ];
      const collectedBasanMarkerList =
        this.createCollectedBasanMarkerList(basanList);
      collectedBasanMarkerList.forEach((marker) => {
        marker.addTo(this.collectedBasanLayer);
      });
    },
    removeCollectedBasan() {
      this.collectedBasanLayer.removeLayer(this.clickedBasan);
    },
    initBasanLayer(basanList) {
      if (!this.basanLayer) {
        this.basanLayer = this.map.createLayerGroup();
        this.map.addLayer(this.basanLayer);
      } else {
        this.basanLayer.clearLayers();
      }
      const basanMarkerList = this.createBasanMarkerList(basanList);
      basanMarkerList.forEach((marker) => {
        marker.addTo(this.basanLayer);
      });
    },
    createBasanMarkerList(basanList) {
      const list = [];
      if (!basanList || basanList.length == 0) {
        return list;
      }
      basanList.forEach((basan) => {
        const latlng = { lat: basan.lat, lng: basan.lng };
        const marker = L.marker(latlng, {
          icon: L.divIcon({
            html: `<i class="iconfont icon-fishing-spot-1 basan-bubble"><i class="iconfont icon-a-Group192 basan-fish"></i></i>`,
          }),
          keyboard: false,
          title: "钓点",
          id: basan.gid,
        });
        marker.on("click", (e) => {
          this.resetClickedBasan();
          marker.setIcon(
            L.divIcon({
              html: `<i class="iconfont icon-fishing-spot-1 basan-bubble basan-clicked"><i class="iconfont icon-a-Group192 basan-fish"></i></i>`,
            })
          );
          this.clickedBasan = marker;
          this.$refs.basanInfoRef.show(marker.options.id, latlng);
        });
        list.push(marker);
      });
      return list;
    },
    createCollectedBasanMarkerList(basanList) {
      const list = [];
      if (!basanList || basanList.length == 0) {
        return list;
      }
      basanList.forEach((basan) => {
        const latlng = { lat: basan.lat, lng: basan.lng };
        const marker = L.marker(latlng, {
          icon: L.divIcon({
            html: `<i class="iconfont icon-fishing-spot-1 basan-bubble collected-basan"><i class="iconfont icon-a-Group192 basan-fish"></i></i>`,
          }),
          keyboard: false,
          title: "收藏钓点",
          id: basan.id,
        });
        marker.on("click", (e) => {
          this.resetClickedBasan();
          marker.setIcon(
            L.divIcon({
              html: `<i class="iconfont icon-fishing-spot-1 basan-bubble basan-clicked"><i class="iconfont icon-a-Group192 basan-fish"></i></i>`,
            })
          );
          this.clickedBasan = marker;
          this.$refs.collectedBasanInfoRef.show(marker.options.id, latlng);
        });
        list.push(marker);
      });
      return list;
    },
    resetClickedBasan() {
      if (this.clickedBasan) {
        const html =
          this.clickedBasan.options.title == "钓点"
            ? `<i class="iconfont icon-fishing-spot-1 basan-bubble"><i class="iconfont icon-a-Group192 basan-fish"></i></i>`
            : `<i class="iconfont icon-fishing-spot-1 basan-bubble collected-basan"><i class="iconfont icon-a-Group192 basan-fish"></i></i>`;
        this.clickedBasan.setIcon(L.divIcon({ html }));
      }
    },
    setMapListen() {
      this.map.on("move", () => {
        const center = this.map.wrapLatLng(this.map.getCenter());
        const oceanDataList = this.map.getOceanDataByLatlng(
          this.map.wrapLatLng(this.map.getCenter())
        );
        const oceanData = oceanDataList.find(
          (data) =>
            data.name == this.$store.state.oceanFeature.feature.displayName
        );
        if (oceanData) {
          this.$store.commit(
            "oceanFeature/updateCurrentOceanFeatureValue",
            Number(oceanData.value)
          );
        }
        this.$store.commit("oceanFeature/updateOceanFeatureData", {
          oceanDataList,
          oceanFeatureList: this.oceanFeatureList,
        });
        this.$store.commit("mapState/updateMapCenter", center);
      });
      this.map.on("movestart", () => {
        if (this.moveTimeout) {
          clearTimeout(this.moveTimeout);
        }
        this.$store.commit("mapState/updateMapMoveState", true);
      });
      this.map.on("moveend", () => {
        this.moveTimeout = setTimeout(() => {
          this.$store.commit("mapState/updateMapMoveState", false);
        }, 2000);
        // this.$store.commit("mapState/updateMapMoveState", false);
      });
      this.map.on("click", (e) => {
        // const popupId = this.$store.state.mapState.popupId;
        // if (popupId) {
        //   const popup = this.map.getLMap()._layers[popupId];
        //   this.map.setPopupContent(e, popup);
        // } else {
        //   this.map.createOceanProductsPopup(e);
        // }
      });
      this.map.on("popupclose", (e) => {
        let popup = e.popup;
        popup.closePopup();
        popup = null;
        this.$store.commit("mapState/setPopupId", null);
      });

      this.$bus.$on(CONSTANTS.EventEnum.TIMECHANGE, (data) => {
        const layer = this.map
          .getProducts()
          .getProductLayerByName(data.oceanFeature.dataName);
        this.map.getProducts().getLoadingBar().show();
        this.map.getProducts().updateLayer(layer, {
          date: data.dateTime.date,
          time: data.dateTime.time,
          depth: 0,
        });
        this.date = data.dateTime.formatDate.split(" ")[0];
      });
      this.$bus.$on(CONSTANTS.EventEnum.RADARSCANNING, (basanList) =>
        this.initBasanLayer(basanList)
      );
      this.$bus.$on(
        CONSTANTS.EventEnum.RESETCLICKEDBASAN,
        this.resetClickedBasan
      );
      this.$bus.$on(CONSTANTS.EventEnum.COLLECTBASAN, this.addCollectedBasan);
      this.$bus.$on(
        CONSTANTS.EventEnum.REMOVECOLLECTEDBASAN,
        this.removeCollectedBasan
      );
    },
    async getBasanList() {
      const result = await basanApi.queryBasanlist(this.date + " 08:00:00");
      if (!result.isOk) {
        console.log(result.msg);
        return [];
      }

      return result.data.features;
    },
  },
};
</script>
<style>
.map-container {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;

  z-index: 0;
}
</style>